//
//  AppDelegate+GQHLocation.m
//  Xanthium
//
//  Created by GuanQinghao on 05/05/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#import "AppDelegate+GQHLocation.h"
#import <objc/message.h>

@implementation AppDelegate (GQHLocation)

/// 检测设备系统地图定位权限
- (void)qh_checkLocationPermissions {
    
    self.qh_locationManager = [[CLLocationManager alloc] init];
    self.qh_locationManager.delegate = self;
    self.qh_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.qh_locationManager.distanceFilter = 500;
    
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog(@"设备启用定位服务");
        
        /// 检测当前应用程序的定位服务权限状态
        CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
        
        if (authorizationStatus == kCLAuthorizationStatusAuthorizedAlways || authorizationStatus == kCLAuthorizationStatusAuthorizedWhenInUse) {
            
            /// 定位服务权限状态为 Always 或 WhenInUse, 开始定位
            [self.qh_locationManager startUpdatingLocation];
        } else {
            
            /// 请求定位服务权限 Always 状态
            if ([self.qh_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                
                [self.qh_locationManager requestAlwaysAuthorization];
            }
        }
    } else {
        NSLog(@"设备未启用定位服务 (关闭定位服务、飞行模式)");
        
        /// 弹窗提醒开启设备定位服务
        
    }
}

/// 动态添加属性值
static char *locationManagerKey = "locatinoManagerKey";
- (void)setQh_locationManager:(CLLocationManager *)qh_locationManager {
    
    objc_setAssociatedObject(self, &locationManagerKey, qh_locationManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CLLocationManager *)qh_locationManager {
    
    return objc_getAssociatedObject(self, &locationManagerKey);
}

@end
